﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ScrewTurn.Wiki;
using ScrewTurn.Wiki.PluginFramework;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;

public partial class Generate : BasePage
{
	/// <summary>
	/// Custom Validator. args.IsValid when no <script> tags are present. 
	/// </summary>
	/// <param name="source"></param>
	/// <param name="args"></param>
	protected void ValidateForScripts(object source, ServerValidateEventArgs args)
	{
		args.IsValid = !Regex.IsMatch(args.Value.ToString(), @"\<script.*?\>");
	}

	protected void Page_Load(object sender, EventArgs e)
	{

		if (!Page.IsPostBack)
		{
			ViewState["SelectedSampleID"] = null;
			ViewState["SelectedSpectrometerID"] = null;


		}
		//if id of experiment is not available redirect to experiment table
		string ExpID = Request["expid"];
		if (Request["expid"] == null) Response.Redirect("Experiments.aspx");

		#region Verify Authentication
		// Re-verify authentication
		PageInfo pageInfo = Pages.Instance.FindPage(Request["Page"]);
		if (pageInfo == null)
		{
			// Page creation
			if (SessionFacade.LoginKey == null && !Settings.PublicAccess)
			{
				Response.Redirect("Login.aspx?Redirect=Generate.aspx?expid=" + Request["expid"]);
			}
			if (!Settings.UsersCanCreateNewPages && !SessionFacade.Admin)
			{
				Response.Redirect("AccessDenied.aspx");
			}
		}
		else
		{
			// Page modification
			if (pageInfo.Provider.ReadOnly) Response.Redirect(pageInfo.Name + Settings.PageExtension);

			if (pageInfo.Status == PageStatus.Locked)
			{
				if (SessionFacade.LoginKey == null || (SessionFacade.LoginKey != null && (SessionFacade.LoginKey == null || !SessionFacade.Admin)))
				{
					Response.Redirect("AccessDenied.aspx");
				}
			}

			// Login/Authorization check
			if (SessionFacade.LoginKey == null && !Settings.PublicAccess && pageInfo.Status != PageStatus.Public)
			{
				Response.Redirect("Login.aspx?Redirect=" + Tools.UrlEncode(Request.Url.ToString().Substring(Request.Url.ToString().ToLowerInvariant().IndexOf("Generate.aspx"))));
			}
			if ((Settings.PublicAccess || pageInfo.Status == PageStatus.Public) && SessionFacade.LoginKey == null)
			{
				//lblIpLogged.Visible = true;
			}
		}
		#endregion



		SamplesDataSource.SelectParameters["username"].DefaultValue = SessionFacade.Username;
		SpectrometersDataSource.SelectParameters["username"].DefaultValue = SessionFacade.Username;
		SampleNamesDataSource.SelectParameters["username"].DefaultValue = SessionFacade.Username;

		ViewState["SelectedExperimentID"] = ExpID;

		//Getting experiment name and content
		SqlConnection MyConnection = new SqlConnection(Constants.NMRExperimentsConStr);
		MyConnection.Open();

		SqlCommand getExperimentByID = MyConnection.CreateCommand();
		getExperimentByID.CommandText = @"
SELECT
	name, 
	[content], 
	dim, 
	version, 
	type
FROM
	experiments
WHERE
	(id = ##id##)".Replace("##id##", ExpID);

		SqlDataReader MyReader = getExperimentByID.ExecuteReader();
		if (!MyReader.HasRows)
		{
			Log.LogEntry("Generate Macro Page. No rows returned by query for ExpID " + ExpID + ".", EntryType.Warning, SessionFacade.Username);
			MyReader.Close();
			MyConnection.Close();
			Response.Redirect("Error.aspx");
		}

		MyReader.Read();
		lblTitle.Text = "Generate Macro for Experiment " + MyReader["name"] + " ver. " + MyReader["version"] + ".";
		lblExperimentName.Text = "<b>" + MyReader["name"] + "</b> Dimentionalyty: <b>" + MyReader["dim"] + "</b>; Type: <b>"
				+ MyReader["type"] + "</b>";

		MyReader.Close();

		MyConnection.Close();
	}

	protected void lbSelectSample_Click(object sender, EventArgs e)
	{
		panSelectionTables.Visible = true;
		mvSelectionTables.ActiveViewIndex = 0;
		SamplesDataSource.DataBind();

	}

	protected void lbSelectSpectrometer_Click(object sender, EventArgs e)
	{
		panSelectionTables.Visible = true;
		mvSelectionTables.ActiveViewIndex = 1;
		SpectrometersDataSource.DataBind();
	}

	protected void SamplesTableGv_RowCommand(object sender, GridViewCommandEventArgs e)
	{
		string currentCommand = e.CommandName;

		if (currentCommand != "SelectSample") return;

		int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());

		string SampleID = SamplesTableGridView.DataKeys[currentRowIndex].Value.ToString();
		string SampleName = drlstSelectSampleName.SelectedItem.Text;
		string SampleVersion = SamplesTableGridView.DataKeys[currentRowIndex].Values[1].ToString();
		string SampleBuffer = SamplesTableGridView.Rows[currentRowIndex].Cells[1].Text;
		string SampleLabeling = SamplesTableGridView.Rows[currentRowIndex].Cells[2].Text;

		lbSelectSample.Text = SampleName + " Ver. " + SampleVersion + " (ID: " + SampleID + "). Buffer: " +
								SampleBuffer + "; Labeling: " + SampleLabeling + ".";

		panSelectionTables.Visible = false;

		ViewState["SelectedSampleID"] = SampleID;
	}

	protected void SpectrometersTableGv_RowCommand(object sender, GridViewCommandEventArgs e)
	{
		string currentCommand = e.CommandName;

		if (currentCommand != "SelectSpectrometer") return;


		int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());

		string SpecID = SpectrometersTableGv.DataKeys[currentRowIndex].Value.ToString();
		string SpecName = SpectrometersTableGv.DataKeys[currentRowIndex].Values[1].ToString();

		string SpecLocation = SpectrometersTableGv.Rows[currentRowIndex].Cells[1].Text;

		lbSelectSpectrometer.Text = SpecName + " (ID: " + SpecID + "). Location: " + SpecLocation + ".";

		panSelectionTables.Visible = false;

		ViewState["SelectedSpectrometerID"] = SpecID;
	}

	protected void RefreshButton_Click(object sender, EventArgs e)
	{
		SamplesDataSource.DataBind();
		SamplesTableGridView.DataBind();
	}

	protected void ButGenerate_Click(object sender, EventArgs e)
	{
		if (!Page.IsValid) return;

		LinkLabel.Visible = true;
		if (ViewState["SelectedSampleID"] == null)
		{
			LinkLabel.Text = "Please select Sample.";
			return;
		}
		if (ViewState["SelectedSpectrometerID"] == null)
		{
			LinkLabel.Text = "Please select Spectrometer.";
			return;
		}

		LinkLabel.Text = "Download: ";

		string NewSetupID = UniBasel.Biozentrum.NMR.GenerateMacro.Generate(ViewState["SelectedExperimentID"].ToString(), ViewState["SelectedSampleID"].ToString(),
										ViewState["SelectedSpectrometerID"].ToString(), tbRemark.Text, SessionFacade.Username);

		LinkToDownloadMacro.Text = "Macro";
		LinkToDownloadMacro.NavigateUrl = "~/GetMacro.aspx?SetupID=" + NewSetupID;
		LinkToDownloadMacro.Visible = true;
	}
}
